<?php
/**
 * Created by andrei
 * Date: 9/11/12
 * Time: 10:35 AM
 */

class Page_Be_Accounts_Login extends Page {
	function __construct() {
		parent::__construct();
	}

	public function defaultAction() {
		if (self::$USER) {
			return array(
				'type' => 'redirect',
				'content' => '/'
			);
		}
		self::$TPL->appendJsFile('admin/login');
		self::$TPL->setBodyTemplate('login_form');
		return array(
			'type' => 'display'
		);
	}

	public function loginAction() {
		if (self::$USER) {
			return array(
				'type' => 'redirect',
				'content' => '/'
			);
		}
		$username = post('username', 'str');
		$password = post('password', 'str');

		if (!$username || !$password) {
			$this->message = t(T_MESSAGE_RESULT, 'no_data');
			$this->error = true;
			return array(
				'type' => 'redirect',
				'query' => false
			);
		}

		$password = md5(HASH.$password.HASH);
		if($userDates = Db_Accounts_Users::getUser($username, $password)) {
			// Logging in the user
			self::$S->Set('login_username', $username);
			self::$S->Set('login_password', $password);
			self::$S->Set('login_timestamp', time());
			if (post('remember', 'bool')) {
				self::$S->Set('login_lifetime', conf('SESSION_LOGIN_LONG_LIFETIME'));
			} else {
				self::$S->Set('login_lifetime', conf('SESSION_LOGIN_SHORT_LIFETIME'));
			}
		} else {
			$this->message = t(T_MESSAGE_RESULT, 'wrong_username_password');
			$this->error = true;
			return array(
				'type' => 'redirect',
				'query' => false
			);
		}

		if ($usPageUrl = self::$S->Get('login_redirect_url')) {
			 self::$S->Remove('login_redirect_url');
		} else {
			$usPageUrl = '/';
		}
		return array(
			'type' => 'redirect',
			'content' => $usPageUrl
		);
	}

	public function logoutAction() {
		self::$S->Remove();
		return array(
			'type' => 'redirect',
			'query' => false
		);
	}

}